﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebeTerm.Common;
using System.Web.Script.Serialization;
using WebeTerm.WebControls;
using System.Web.SessionState;

namespace WebeTerm.Web.AjaxHandler
{
    /// <summary>
    /// AjaxHandler 的摘要说明
    /// </summary>
    public class ControlHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            BindList(context);
        }

        private void BindList(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Expires = 60; //1个小时
            JavaScriptSerializer jss = new JavaScriptSerializer();
            Dictionary<string, object> paras = jss.DeserializeObject(context.Request["Parameters"]) as Dictionary<string, object>;
            ViewManager<ControlBase> viewManager = new ViewManager<ControlBase>();
            ControlBase control = viewManager.LoadViewControl(GetValue(paras, "ControlFile"));
            control.Parameters = paras;
            context.Response.Write(viewManager.RenderView());
        }

        private string GetValue(Dictionary<string, object> paras, string paraName)
        {
            IEnumerable<KeyValuePair<string, object>> para = paras.Where(it => it.Key == paraName);
            if (para.Count() == 0) return null;
            return Convert.ToString(para.FirstOrDefault().Value);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}